package com.tcu.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcu.exception.SmartException;
import com.tcu.order.entity.Order;
import com.tcu.order.entity.OrderItem;
import com.tcu.order.entity.OrderPicture;
import com.tcu.order.entity.OrderVideo;
import com.tcu.order.entity.bo.OrderBo;
import com.tcu.order.mapper.OrderMapper;
import com.tcu.order.service.IOrderItemService;
import com.tcu.order.service.IOrderPictureService;
import com.tcu.order.service.IOrderService;
import com.tcu.order.service.IOrderVideoService;
import com.tcu.part.service.IPartNumService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    private IOrderVideoService videoService;
    private IOrderPictureService pictureService;
    private IOrderItemService itemService;
    private IPartNumService partNumService;


    @Override
    public OrderBo getOrderInfoById(String orderId) {
        OrderBo ob = new OrderBo();
        List<OrderVideo> videosByOrderId = videoService.getVideosByOrderId(orderId);
        List<OrderPicture> picturesByOrderId = pictureService.getPicturesByOrderId(orderId);
        List<OrderItem> allItemByOid = itemService.getAllItemByOid(orderId);
        Order order = baseMapper.selectById(orderId);
        BeanUtils.copyProperties(order,ob);
        ob.setOrderPictures(picturesByOrderId);
        ob.setOrderVideos(videosByOrderId);
        ob.setOrderItemList(allItemByOid);
        return ob;
    }

    @Override
    @Transactional
    public void saveOrderWithItems(Order o, List<OrderItem> itemList) {
        AtomicReference<Double> totalPrice = new AtomicReference<>(0.0);
        itemList.forEach(item->{
            totalPrice.set(item.getItemPrice() + totalPrice.get());
            if (item.getPartId()!=null&&Integer.valueOf(item.getPartNum())>0) {
                // 如果设计到零件类型，要进行数量的控制
                partNumService.consumePart(item.getPartId(), Integer.valueOf(item.getPartNum()));
            }
        });
//        以 零件项 的价格为准
        if(o.getTotalPrice()!=totalPrice.get()){
            o.setTotalPrice(totalPrice.get());
        }
        itemService.saveBatch(itemList);
        save(o);
    }

    @Override
    @Transactional
    public void deleteOrder(String orderId) {
        itemService.deleteItemByOid(orderId);
        removeById(orderId);
    }

    @Override
    @Transactional
    public void updateOrder(Order o, List<OrderItem> itemList) {
        if(o.getId()==null){
            throw new SmartException(20001,"更新时，id为null，无法更新");
        }
        AtomicReference<Double> totalPrice = new AtomicReference<>(0.0);
        itemList.forEach(item->{
            totalPrice.set(item.getItemPrice() + totalPrice.get());
        });
//        以 零件项 的价格为准
        if(o.getTotalPrice()!=totalPrice.get()){
            o.setTotalPrice(totalPrice.get());
        }
        // 如果订单项是 零件的话，进行数量回滚。
        List<OrderItem> allItemByOid = itemService.getAllItemByOid(o.getId());
        allItemByOid.forEach(item->{
            if (item.getPartId()!=null&&Integer.valueOf(item.getPartNum())>0) {
                partNumService.rollBackPart(item.getPartId(), Integer.valueOf(item.getPartNum()));
            }
        });
        // 删除各个订单项
        itemService.deleteItemByOid(o.getId());
//        保存新的订单项
        itemService.saveBatch(itemList);
//        更新订单
        updateById(o);
    }

    @Override
    public void changeStatus(String orderId, Integer value) {
        Order byId = getById(orderId);
        byId.setStatus(value);
        updateById(byId);
    }

    @Override
    public List<OrderBo> getChildrenOrder(String orderParentId) {
        List<OrderBo> repairOrders = new ArrayList<>();
        String parent = orderParentId;
        while (hasChildren(parent)){
            QueryWrapper<Order>wrapper = new QueryWrapper<>();
            wrapper.eq("order_parent_id",parent);
//            因为 hasChildren 为true，所以，必定存在
            Order repairOrder = baseMapper.selectOne(wrapper);
            OrderBo orderInfoById = getOrderInfoById(repairOrder.getId());
            repairOrders.add(orderInfoById);
            parent = repairOrder.getId();
        }
        return repairOrders;

    }

    @Override
    public boolean hasChildren(String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_parent_id",orderId);
        Order order = baseMapper.selectOne(wrapper);
        return (order!=null);
    }

    // 结束订单，进行后续操作。
    @Override
    public boolean endOrder(String orderId, String workerId) {
        return false;
    }

//    维修人员 接单。。。
    @Override
    public void formalReceive(String orderId, String workerId) {
        Order byId = getById(orderId);
        byId.setWorkerId(workerId);
        updateById(byId);
    }

    @Autowired
    public void setVideoService(IOrderVideoService videoService) {
        this.videoService = videoService;
    }
    @Autowired
    public void setPictureService(IOrderPictureService pictureService) {
        this.pictureService = pictureService;
    }
    @Autowired
    public void setItemService(IOrderItemService itemService) {
        this.itemService = itemService;
    }

    @Autowired
    public void setPartNumService(IPartNumService partNumService) {
        this.partNumService = partNumService;
    }
}
